# -*- coding: utf-8 -*-
import os
import smtplib
from email.mime.text import MIMEText
from email.header import Header

class EmailNotifier:
    """
    通过SMTP发送邮件告警的通知器。
    """
    def __init__(self):
        """
        初始化邮件通知器，从环境变量加载SMTP配置。
        """
        self.smtp_host = os.getenv("SMTP_HOST")
        self.smtp_port = int(os.getenv("SMTP_PORT", 587))  # 默认使用587端口 (TLS)
        self.smtp_user = os.getenv("SMTP_USER")
        self.smtp_password = os.getenv("SMTP_PASSWORD")
        self.sender_email = os.getenv("SMTP_SENDER_EMAIL")

        if not all([self.smtp_host, self.smtp_port, self.smtp_user, self.smtp_password, self.sender_email]):
            raise ValueError("请配置完整的SMTP环境变量: SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, SMTP_SENDER_EMAIL")

    def send_email(self, recipient_email, subject, body):
        """
        发送邮件。

        :param recipient_email: 收件人邮箱地址
        :param subject: 邮件主题
        :param body: 邮件正文 (纯文本)
        :return: (bool, str) 发送是否成功以及消息
        """
        message = MIMEText(body, 'plain', 'utf-8')
        message['From'] = Header(f"DeepGuard告警系统 <{self.sender_email}>", 'utf-8')
        message['To'] = Header(recipient_email, 'utf-8')
        message['Subject'] = Header(subject, 'utf-8')

        try:
            print(f"📧 准备发送邮件至 {recipient_email}...")
            print(f"   - SMTP服务器: {self.smtp_host}:{self.smtp_port}")
            print(f"   - 发件人: {self.sender_email}")

            # 根据端口判断是否使用SSL/TLS
            if self.smtp_port == 465:
                server = smtplib.SMTP_SSL(self.smtp_host, self.smtp_port, timeout=15)
            else:
                server = smtplib.SMTP(self.smtp_host, self.smtp_port, timeout=15)
                server.starttls()  # 升级到TLS连接

            server.login(self.smtp_user, self.smtp_password)
            server.sendmail(self.sender_email, [recipient_email], message.as_string())
            server.quit()
            
            print("✅ 邮件发送成功。")
            return True, "邮件发送成功"
        except smtplib.SMTPException as e:
            error_message = f"❌ 发送邮件失败: {e}"
            print(error_message)
            return False, error_message
        except Exception as e:
            error_message = f"❌ 发送邮件时发生未知错误: {e}"
            print(error_message)
            return False, error_message